package org.example.c4;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * ABA问题
 * 通过AtomicStampedReference解决ABA问题
 */

@Slf4j
public class Demo3 {
    static AtomicStampedReference<String> str;

    public static void main(String[] args) {
        str = new AtomicStampedReference<>("A", 1);
        final String old = str.getReference();
        final int version = str.getStamp();

        doOther();

        log.info("A -> C {}", str.compareAndSet(old, "c", version, version + 1));
    }

    private static void doOther() {
        final Thread t1 = new Thread(() -> {
            String old = str.getReference();
            int version = str.getStamp();
            log.info("{} -> B {}", old, str.compareAndSet(old, "B", version, version + 1));

            old = str.getReference();
            version = str.getStamp();
            log.info("{} -> A {}", old, str.compareAndSet(old, "A", version, version + 1));
        }, "t1");

        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
        }
    }
}
